<template>
  <div class="component-container feature-out">
    <div ref="searchDiv">
      <div class="filter-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="small"
          align="left"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          class="filter-item"
          style="width: 360px;"
          @change="onDatePickerChange"
        ></el-date-picker>
        <el-select
          size="small"
          class="filter-item"
          placeholder="请选择启用状态"
          v-model="listQuery.status"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input
          v-model="listQuery.keyword"
          size="small"
          class="filter-item"
          placeholder="请输入关键词"
          style="width: 200px;"
        ></el-input>
        <el-button
          @click="handleQuery"
          type="primary"
          size="small"
          class="filter-item"
          ref="btnQuery"
          >查询</el-button
        >
        <el-button
          @click="handleClear"
          size="small"
          class="filter-item"
          type="primary"
          ref="btnRefresh"
          >重置</el-button
        >
      </div>
      <el-button
        size="small"
        @click="sync"
        type="primary"
        style="margin-bottom: 12px;"
      >
        同步预警知识包
      </el-button>
    </div>

    <el-table
      :data="list"
      highlight-current-row
      :max-height="tableHeight"
      style="width: 100%;margin-bottom: 12px;"
    >
      <el-table-column
        label="预警知识包"
        prop="package_name"
        align="center"
        min-width="180px"
      ></el-table-column>
      <el-table-column
        label="描述"
        prop="name"
        align="center"
        min-width="180px"
      ></el-table-column>
      <el-table-column label="启用状态" align="center" min-width="90px">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '1' ? 'success' : 'info'"
            effect="light"
            size="mini"
          >
            {{ scope.row.status === '1' ? '已启用' : '未启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        prop="creator"
        align="center"
        min-width="100px"
      ></el-table-column>
      <el-table-column
        label="版本"
        prop="version"
        align="center"
        min-width="80px"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="create_time"
        align="center"
        min-width="160px"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="190px">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="editTriggerRule(scope.row)"
            class="click-btn"
          >
            预警任务配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.current_page"
        :page-sizes="[10, 20, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog
      title="预警任务配置"
      :visible="showTriggerRuleDialog"
      :before-close="cancelTiggerRuleDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <el-form label-width="100px">
        <el-form-item label="预警触发条件:">
          <el-checkbox-group v-model="triggerType">
            <el-checkbox :label="1">进件触发</el-checkbox>
            <el-checkbox :label="2">提现触发</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="处置方式:">
          <el-checkbox-group
            v-model="checkedTouchs"
            @change="handleTouchChange"
          >
            <el-form-item>
              <el-checkbox label="1" @change="handleMessageChange">
                短信通知
              </el-checkbox>
              <div class="form-item-wrap">
                <el-radio-group
                  v-model="touchFrequence"
                  @change="handletouchFrequenceChange"
                >
                  <el-radio label="everyday">一天发送1条</el-radio>
                  <el-radio label="everytime">每次触发都发送</el-radio>
                </el-radio-group>
                <el-input
                  type="textarea"
                  placeholder="请输入手机号码，支持输入多个，用逗号分开"
                  v-model="touchValues"
                  show-word-limit
                  :disabled="touchFrequence === ''"
                ></el-input>
              </div>
              <el-checkbox label="2" @change="isTouchEmailChange">
                邮件通知
              </el-checkbox>
              <div class="form-item-wrap">
                <el-radio-group
                  v-model="touchEmailFreq"
                  @change="handletouchEmailFreqChange"
                >
                  <el-radio label="everyday">一天发送1条</el-radio>
                  <el-radio label="everytime">每次触发都发送</el-radio>
                </el-radio-group>
                <el-input
                  type="textarea"
                  placeholder="请输入邮箱，支持输入多个，用逗号分开"
                  v-model="emailTosValue"
                  show-word-limit
                  :disabled="touchEmailFreq === ''"
                ></el-input>
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox label="3">人工审批</el-checkbox>
            </el-form-item>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否启用:">
          <el-checkbox v-model="status"></el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelTiggerRuleDialog"
          >取 消</el-button
        >
        <el-button size="small" type="primary" @click="handleTriggerRuleSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import TitleContainer from '@/components/title/TitleContainer.vue'
import {
  getConfigList,
  changeStatus,
  triggerSave,
  touchSave,
  sync,
  update
} from '@/api/risksystem/riskWarning/task/index'
@Component({
  name: 'trustTrial',
  components: {
    //引用的组件在这里声明
    TitleContainer
  }
})
export default class extends Vue {
  private dateRange = []
  private checkedDmpConfig: any = {}
  private triggerType: any = [] // 触发条件
  private triggerTimingValue = ''
  private checkedTouchs: any = [] // 处置方式
  private touchFrequence: any = '' // 短信发送方式
  private touchEmailFreq: any = '' // 邮件发送方式
  private touchValues = '' // 手机号
  private emailTosValue = '' // 邮件信息
  private status = false
  private timingMinuteValue = '10'
  private timingDayValue: any = '20:00:00'
  private options = [
    { label: '全部', value: '' },
    { label: '启用', value: 1 },
    { label: '未启用', value: 0 }
  ]
  private tableHeight: any = null
  private list = []

  private listQuery: any = {
    status: undefined,
    keyword: undefined,
    start: this.dateRange[0],
    end: this.dateRange[1],
    limit: 10,
    current_page: 1
  }
  private total = 0
  private tableLoading = false
  private showTriggerRuleDialog = false
  private showTouchRuleDialog = false

  @Watch('dateRange')
  private onDatePickerChange(value: boolean) {
    this.listQuery.start = this.dateRange ? this.dateRange[0] : undefined
    this.listQuery.end = this.dateRange ? this.dateRange[1] : undefined
  }
  created() {
    this.getList()
  }
  mounted() {
    this.init()
  }
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  }
  // 表格高度
  private init() {
    var _this = this
    this.$nextTick(() => {
      this.tableHeight =
        window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 230
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 230
      })
    }
  }
  private handleClear() {
    this.dateRange = []
    this.listQuery = {
      status: undefined,
      keyword: undefined,
      start: undefined,
      end: undefined,
      limit: 10,
      current_page: 1
    }
    this.getList()
  }
  private handleQuery() {
    this.listQuery.current_page = 1
    this.getList()
  }
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.listQuery.current_page = val
    this.getList()
  }
  // size切换查询
  handleSizeChange(val: any) {
    this.listQuery.limit = val
    this.getList()
  }
  //  修改启用状态
  private async changeTaskStatus($event: any, id: any) {
    var data = {
      id,
      status: $event === 'active' ? 1 : 0
    }
    const statusRes = await changeStatus(data)
    if (statusRes.data.code === 1) {
      this.$message.error('修改失败')
    } else {
      this.getList()
      this.$message.success('修改成功')
    }
  }
  // 触发条件
  private editTriggerRule(row: any) {
    this.checkedDmpConfig = {}
    var _this = this
    this.showTriggerRuleDialog = true
    this.triggerType = []
    this.touchValues = ''
    this.emailTosValue = ''
    this.checkedDmpConfig = row
    this.status = this.checkedDmpConfig.status === '1' ? true : false
    if (this.checkedDmpConfig.triggers.length) {
      this.checkedDmpConfig.triggers.forEach(function(item: any) {
        if (item.status === '1') {
          _this.status = true
        }
        if (item.is_selected === '1') {
          _this.triggerType.push(Number(item.trigger_type))
        }
      })
    }
    // 配置处置方式
    if (this.checkedDmpConfig.touches.length) {
      this.checkedDmpConfig.touches.forEach(function(item: any) {
        // 判断选中规则
        // 开启状态
        if (item.is_selected === '1') {
          _this.checkedTouchs.push(item.touch_type)
        }
        if (item.touch_type === '1' && item.is_selected === '1') {
          _this.touchFrequence = item.freq_type
        }
        if (item.touch_type === '1') {
          _this.touchValues = item.touch_value
        }
        if (item.touch_type === '2' && item.is_selected === '1') {
          _this.touchEmailFreq = item.freq_type
        }
        if (item.touch_type === '2') {
          _this.emailTosValue = item.touch_value
        }
        if (item.touch_type === '3' && item.is_selected === '1') {
          // _this.touchValues = item.touch_value
          _this.checkedTouchs.push(item.touch_type)
        }
      })
    }
  }
  // 定时触发方式
  private handleTriggerTimingChange(val: any) {
    if (!val) this.triggerTimingValue = ''
  }
  private handleTriggerTimingOptionChange() {
    if (this.triggerType.indexOf(3) === -1) this.triggerType.push(3)
  }
  // 提交
  private handleTriggerRuleSubmit() {
    if (this.checkedTouchs.indexOf('1') !== -1) {
      if (this.touchValues === '') {
        this.$message.error('请填写手机号！')
        return false
      }
    }
    if (this.checkedTouchs.indexOf('2') !== -1) {
      if (this.emailTosValue === '') {
        this.$message.error('请填写邮箱！')
        return false
      }
    }
    var data = {
      id: this.checkedDmpConfig.id,
      triggerTypes: this.triggerType,
      freq: {
        freq_type: this.triggerTimingValue,
        freq_value:
          this.triggerTimingValue === 'min'
            ? this.timingMinuteValue
            : this.triggerTimingValue === 'day'
            ? this.timingDayValue
            : ''
      },
      touch: this.checkedTouchs,
      touchSmsMobiles: this.touchValues,
      touchEmailTos: this.emailTosValue,
      touchSmsFreq: this.touchFrequence,
      touchEmailFreq: this.touchEmailFreq,
      isTouchManual: this.checkedTouchs.indexOf('3') !== -1 ? 1 : 0, // 是否启用人工审核
      isTouchSms: this.checkedTouchs.indexOf('1') !== -1 ? 1 : 0, // 是否启用短信发送
      isTouchEmail: this.checkedTouchs.indexOf('2') !== -1 ? 1 : 0, // 是否启用邮件发送
      status: this.status ? 1 : 0
    }
    this.update(data)
  }
  private async update(data: any) {
    const res: any = await update(data)
    if (res.code === 0) {
      this.cancelTiggerRuleDialog()
      this.getList()
      this.$message.success('设置成功！')
    } else {
      this.$confirm(
        '进件/支用预警有且只能有一个预警任务进行',
        '进件预警已设置，请先停用',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
  private cancelTiggerRuleDialog() {
    this.showTriggerRuleDialog = false
    this.cancelTouchRuleDialog()
    this.checkedDmpConfig = {}
    this.triggerType = []
    this.timingMinuteValue = '10'
    this.timingDayValue = '20:00:00'
    this.triggerTimingValue = ''
  }
  private cancelTouchRuleDialog() {
    this.showTouchRuleDialog = false
    this.touchValues = ''
    this.emailTosValue = ''
    this.checkedDmpConfig = {}
    this.checkedTouchs = []
    this.touchFrequence = ''
    this.touchEmailFreq = ''
  }
  // // 处置方式
  // private async handleTouchRuleSubmit() {
  //   const res: any = await touchSave({
  //     id: this.checkedDmpConfig.id,
  //     touch: this.checkedTouchs,
  //     touch_values: this.touchValues,
  //     frequence: this.touchFrequence
  //   })
  //   if (res.code === 0) {
  //     this.cancelTouchRuleDialog()
  //     this.getList()
  //     this.$message.success('设置成功！')
  //   }
  // }
  // 选项切换
  private handletouchFrequenceChange() {
    if (this.checkedTouchs.indexOf('1') === -1) {
      this.checkedTouchs.push('1')
    }
  }
  private handletouchEmailFreqChange() {
    if (this.checkedTouchs.indexOf('2') === -1) {
      this.touchEmailFreq.push('1')
    }
  }
  private handleMessageChange(val: any) {
    this.touchFrequence = val === true ? 'everyday' : ''
  }
  private isTouchEmailChange(val: any) {
    this.touchEmailFreq = val === true ? 'everyday' : ''
  }
  private handleTouchChange() {
    if (this.checkedTouchs.indexOf('1') === -1) {
      this.touchFrequence = ''
    }
    if (this.checkedTouchs.indexOf('2') === -1) {
      this.touchEmailFreq = ''
    }
  }
  private async getList() {
    // 加载数据
    this.tableLoading = true
    const configres = await getConfigList({ search: this.listQuery })
    this.list = configres.data.list
    this.total = Number(configres.data.count)
  }
  private async sync() {
    // 加载数据
    const res: any = await sync()
    if (res.code === 0) {
      this.$message.success('刷新成功！')
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.component-container {
  padding: 20px;
  position: relative;
}
.form-item-wrap {
  padding: 0 20px;
}
.timing-options {
  padding: 0 0 0 40px;
  .timing-option-item {
    padding: 5px 0;
    input {
      border: 1px solid #ccc;
      box-shadow: none;
      width: 70px;
      padding: 3px 5px;
    }
  }
}
</style>
